package com.sd.util;

import java.util.Vector;

import android.content.Context;

import com.alex.books.BaseBook;
import com.alex.books.BookStore;
import com.alex.database.BookDao;
import com.sd.activity.r.R;
import com.sd.view.ToastManager;

/**
 * 书籍
 * @author Administrator
 *
 */
public class BookCabin {
	//书籍
	private Vector<BaseBook> books;
	
	private static BookCabin instance;
	
	public static BookCabin getInstance(){
		if(instance == null){
			instance = new BookCabin();
		}
		return instance;
	}
	
	public Vector<BaseBook> getBooks(){
		return books;
	}
	
	public void refresh(Context context,String chars){
		String orderBy = "book_attach1 desc, book_lasttime desc";
		Vector<BaseBook> tempBooks = BookStore.getInstance().getBooks(context,chars,orderBy);
		books.clear();
		for(int i=0;i<tempBooks.size();i++){
			books.add(tempBooks.get(i));
		}
	}
	
	private BookCabin(){
		books = new Vector<BaseBook>();
	}
	
	
	public Vector<BaseBook> getBooks(Context context,String chars){
		refresh(context,chars);
		return books;
	}
	
	public boolean isInBookCabin(BaseBook book){
		boolean is = false;
		for(int i=0;i<books.size();i++){
			if(book.mBookPath.equals(books.get(i).mBookPath)){
				is = true;
				break;
			}
		}
		return is;
	}
	
	public boolean checkBookCabin(String path){
		boolean is = false;
		for(int i=0;i<books.size();i++){
			if(path.equals(books.get(i).mBookPath)){
				is = true;
				break;
			}
		}
		return is;
	}
	
	public boolean removeBook(Context context,int bookId){
		BaseBook book = null;
		for(int i=0;i<books.size();i++){
			book = books.get(i);
			if(book.mBookId == bookId){
				return removeBook(context, book);
			}
		}
		return false;
	}
	
	
	public boolean removeBook(Context context,BaseBook book){
		if(book.mAttach1 !=null && book.mAttach1.equals("1")){
			ToastManager.getInstance().showText(context, R.string.msg_system_book);
		}else{
			int reslut = BookDao.getInstance().deleteBook(context, book);
			int reslut1 = BookDao.getInstance().deleteBookMarksByBookId(context,book.mBookId);
			int reslut2 = BookDao.getInstance().deleteChapter(context, book.mBookId);
			books.remove(book);
		}
		
		return true;
	}
	
	public boolean removeBook(Context context,String dir){
		BaseBook book = null;
		for(int i=0;i<books.size();i++){
			book = books.get(i);
			if(book.mBookPath.equals(dir)){
				return removeBook(context, book);
			}
		}
		return false;
	}
	
	public void addBook(BaseBook book){
		books.add(book);
	}
	
	
	public void cleanAllBook(Context context){
		int size = books.size();
		for(int i=size-1;i>=0;i--){
			BaseBook book = books.get(i);
			if(book.mAttach1!=null &&  book.mAttach1.equals("1")){
			}else{
				BookStore.getInstance().deleteBook(context, books.get(i));
				books.remove(i);
			}
		}
	}
}
